<template>
  <!-- 首页顶部直通车组件 -->
  <div class="top-bar">
    <div class="wrap">
      <div class="l">欢迎来到叩丁狼积分商城</div>
      <div class="r">
        <ul>
          <li>
            <img
              class="avatar"
              :src="userInfo.headImg"
              @click="clickAvatar"
            />
          </li>
          <li>用户名：{{userInfo.nickName}}</li>
          <li>我的积分：{{userInfo.coin}}</li>
          <li>获取积分</li>
          <li>扣丁狼官网</li>
          <li class="cart-btn btn" v-show="isLogined">
            <img src="../../assets/img/cart.png" alt="" width="20">
            <span>购物车</span>
            <b>{{cartTotal}}</b>
          </li>
          <li class="login-btn btn" @click="changeIsShowLoginModel(true)" v-show="!isLogined">登录</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";

// 请求api相关
import { WeixinLoginApi } from "@/request/loginApi.js";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
    };
  },
  computed: {
    ...mapState({
      isLogined: state => state.loginStatus.isLogined,
      cartTotal: state => state.userInfo.cartTotal,
      userInfo: state => state.userInfo.userInfo
    })
  },
  created() {
    this.setUserLoginState()
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModel: "isShowLogin/changeIsShowLoginModel",
      changeIsShowToast: "toastStatus/changeIsShowToast",
      changeIsLogin: 'loginStatus/changeIsLogin',
      initUserInfo: 'userInfo/initUserInfo'
    }),
    ...mapActions({
      asyncChangeIsShowToast: 'toastStatus/asyncChangeIsShowToast',
      asyncUpdateUserInfo: 'userInfo/asyncUpdateUserInfo'
    }),
    // 点击头像
    clickAvatar(){
      // this.asyncChangeIsShowToast({
      //   msg:'请登录',
      //   type:'info'
      // })

      if(this.isLogined){
        this.$router.push('/user')
      }
    },
    // 设置用户登陆状态方法
    setUserLoginState(){
      setTimeout(async ()=>{
        // 获取微信扫码用户同意后，页面会刷新然后在query上带一个code。拿着这个code给后端发起请求
        let code = this.$route.query.code 
        if(code){
          // 有code
          // 用code向后端发起微信授权登录
          let res = await WeixinLoginApi({code})

          if(res.code==0){
            // 1.提示成功  
            this.asyncChangeIsShowToast({
              msg: '手机号码格式不正确',
              type: 'info'
            })

            // 2.存token
            localStorage.setItem("x-auth-token", res["x-auth-token"])

            // 3.改变vuex登录状态
            this.changeIsLogin(true)

            // 4、清除浏览器地址栏上的code
            this.$router.push(this.$route.path)

            // 5.更新用户信息
            this.asyncUpdateUserInfo()

          }else{
            // 登录失败情况
            this.asyncChangeIsShowToast({
              msg: res.message,
              type: 'info'
            })
          }
        }else{
          // 没有code，说明用户没有扫码 或者 用户已经登录过
          // 所以还需要判断有没有token，然后设置登录状态
          let token =  localStorage.getItem('x-auth-token')
          this.changeIsLogin(Boolean(token))

          // 登陆过  --  获取用户信息
          if(token){
            this.asyncUpdateUserInfo()
          }else{
            // 没登录 -- 用户信息初始化(登出)
            this.initUserInfo()
          }
        }
      },500)
    }
  },
  // watch:{
  //   // 路由监听
  //   "$route.path":{
  //     handler(newVal,oldVal){
  //       console.log(newVal,oldVal)
  //       this.setUserLoginState()
  //     }
  //   }
  // }
};
</script>

<style scoped lang="less">
@import url("../../assets/css/public.less");
.top-bar {
  height: 40px;
  background: #242b39;

  .wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    font-size: 14px;
    font-family: SourceHanSansSC;
    font-weight: 300;
    color: #fffefe;

    .l {
      height: 100%;
      line-height: 40px;
    }

    .r ul {
      display: flex;
      align-items: center;

      li {
        display: flex;
        align-items: center;
        margin-left: 20px;
        cursor: pointer;

        .avatar {
          margin-right: 10px;
          width: 26px;
          height: 26px;
          background: #7d8696;
          border: 1px solid #8891a1;
          border-radius: 13px;
        }

        &.btn {
          width: 124px;
          height: 40px;
          text-align: center;
          background: @base-color;
          display: flex;
          justify-content: center;
        }

        &.cart-btn{
          align-items: center;

          span{
            margin: 0 5px;
          }

          b{
            width: 22px;
            height: 22px;
            line-height: 22px;
            background-color: #fd604d;
            border-radius: 50%;
            text-align: center;
          }
        }
      }
    }
  }
}
</style>